<?php

namespace addons\shopro\controller;

use addons\recharge\model\MoneyLog;
use addons\shopro\model\Dispatch;
use addons\shopro\model\DispatchSelfetch;
use addons\shopro\model\User;
use addons\shopro\model\UserOauth;
use addons\vip\library\OrderException;
use addons\vip\library\Service;
use addons\vip\model\Record;
use addons\vip\model\Vip as VipModel;
use think\Db;
use think\Exception;

class Vip extends Base
{

    protected $noNeedLogin = ['index','epay'];
    protected $noNeedRight = ['*'];

    /**
     * VIP列表
     */
    public function index()
    {
        $config = get_addon_config('vip');
        $dataList = VipModel::where('status', 'normal')->field('sales', true)->order('level', 'asc')->select();
        $vipInfo = Service::getVipInfo();
        $vipInfo = $vipInfo ?: null;
        $vipList = [];
        foreach ($dataList as $index => $item) {
            $rightdata = $item['rightdata'];
            foreach ($rightdata as &$res) {
                $res['image'] = cdnurl($res['image'], true);
            }
            $pricedata = $item['pricedata'];
            foreach ($pricedata as &$v){
                $v['is_repair'] = 0;
                if($vipInfo && $v['price'] > $vipInfo['price']){
                    $v['price'] = $v['price'] - $vipInfo['price'];
                    $v['is_repair'] = 1;
                }
            }
            $recordInfo = Record::where('user_id',$this->auth->id)->where('level',$item['level'])->find();
            if($recordInfo['is_receive'] == 2){
                $recordInfo['is_receive'] = 2;
                $recordInfo['is_virtual_receive'] = 2;
            }else{
                $recordInfo['is_receive'] = Db::name('vip_receive')->where('user_id',$this->auth->id)->where('level',$item['level'])->where('goods_type','normal')->count() > 0 ? 1 : 0;
                $recordInfo['is_virtual_receive'] = Db::name('vip_receive')->where('user_id',$this->auth->id)->where('level',$item['level'])->where('goods_type','virtual')->count() > 0 ? 1 : 0;
            }

            // if ($vipInfo && $vipInfo['level'] == $item['level']) {
                $item['is_receive'] = isset($recordInfo['is_receive']) ? $recordInfo['is_receive'] : 0;;
                $item['is_virtual_receive'] = isset($recordInfo['is_virtual_receive']) ? $recordInfo['is_virtual_receive'] : 0;
            // }else{
            //     $item['is_receive'] = 0;
            //     $item['is_virtual_receive'] = 0;
            // }
            $vipList[] = [
                'level'     => $item['level'],
                'icon'      => $item['icon'],
                'name'      => $item['name'],
                'image'     => $item['image'],
                'intro'     => $item['intro'],
                'is_receive'     => $item['is_receive'],
                'is_virtual_receive'     => $item['is_virtual_receive'],
                'rightdata' => $rightdata,
                'pricedata' => $pricedata
            ];
        }

        //查询预估收益信息
        if($vipInfo){
            $where = [];
            $where['user_id'] = $this->auth->id;
            $where['type'] = 1;
            //yesterday
            $lastday_money = \addons\shopro\model\UserWalletLog::where($where)->where('memo','每日分红')->whereTime('createtime', 'today')->sum('wallet');
            // $today_money = MoneyLog::where($where)->whereTime('createtime', 'today')->sum('money');
            $vipInfo['lastday_money'] = $lastday_money;
            $where = [];
            $where['order.status'] = ['in',[1,2]];
            $todayPrice = Db::name('shopro_order_item')->alias('item')
                ->join('shopro_order order', 'order.id = item.order_id','left')
                ->join('shopro_goods goods', 'goods.id = item.goods_id','left')
                ->where($where)
                ->where('find_in_set(:id,goods.category_ids)',['id'=>2])
                ->whereTime('order.createtime', 'today')
                ->sum('item.pay_price')*0.1;
            if($vipInfo['level'] == 1){
                $vip1User = Db::name('user')->where('vip',1)->field('id')->count();//398会员数
                $vipInfo['today_money'] = round($todayPrice * 0.02 / $vip1User,2);
            }
            if($vipInfo['level'] == 2){
                $vip2User = Db::name('user')->where('vip',2)->field('id')->count();//398会员数
                $vipInfo['today_money'] = round($todayPrice * 0.03 / $vip2User,2);
            }
            if($vipInfo['level'] == 3){
                $vip3User = Db::name('user')->where('vip',3)->field('id')->count();//398会员数
                $vipInfo['today_money'] = round($todayPrice * 0.05 / $vip3User,2);
            }

            // $vipInfo['today_money'] = $today_money;

        }
        $paytypelist = array_filter(explode(',', $config['paytypelist']));
        $defaultpaytype = $config['defaultpaytype'];
        $defaultpaytype = in_array($defaultpaytype, $paytypelist) ? $defaultpaytype : reset($paytypelist);

        $this->success('', [
            'vipList' => $vipList,
            'vipInfo' => $vipInfo,
            'config'  => [
                'paytypelist'    => $paytypelist,
                'defaultpaytype' => $defaultpaytype
            ]
        ]);
    }

    /**
     * 获取VIP商品
     * @return void
     */
    public function getGoods()
    {
        $level = $this->request->param('level/d');
        $type = $this->request->param('type');
        $virtual = $this->request->param('virtual',1);
        if (!$level) {
            $this->error('请选择VIP等级');
        }
        $vipInfo = VipModel::getByLevel($level);
        if (!$vipInfo) {
            $this->error('未找到VIP相关信息');
        }
        $where = [];
        $where['g.type'] = $type;
        if($virtual == 2){
            $where['g.id'] = ['in',$vipInfo->goods2_ids];
        }else{
            $where['g.id'] = ['in',$vipInfo->goods_ids];
        }

        $goods = \addons\shopro\model\Goods::alias('g')
            ->field('g.*,s.expire_type,s.expire_day,s.expire_time')
            ->join('shopro_dispatch d','d.id=g.dispatch_ids','left')
            ->join('shopro_dispatch_selfetch s','s.id=d.type_ids','left')
            ->where($where)->select();
        foreach ($goods as $key => $value) {
            // 获取配送模板
            $dispatch = Dispatch::where('type', $value['dispatch_type'])->where('id', $value['dispatch_ids'])->find();
            $type_ids = $dispatch['type_ids'] ?? '';
            $dispatch_selfetch_ids = explode(',', $type_ids);
            $dispatchSelfetch = DispatchSelfetch::where('id', 'in', $dispatch_selfetch_ids)
                ->order('id', 'asc')->find();

            $expiretime = null;       // 核销券过期时间
            if ($dispatchSelfetch) {
                if ($dispatchSelfetch['expire_type'] == 'day') {
                    $expire_day = $dispatchSelfetch['expire_day'] > 0 ? $dispatchSelfetch['expire_day'] : 0;
                    $expiretime = $expire_day ? (time() + ($expire_day * 86400)) : null;
                } else {
                    $expiretime = $dispatchSelfetch['expire_time'] ?: null;
                }
            }
            $goods[$key]['expire_time'] = date('Y-m-d H:i:s',$expiretime);
        }

        $goods = $goods ?: null;
        $this->success('', $goods);
    }

    /**
     * vip详情
     * @return void
     */
    public function vipDetails()
    {
        $level = $this->request->param('level/d');
        if (!$level) {
            $this->error('请选择VIP等级');
        }
        $vipInfo = VipModel::getByLevel($level);
        if (!$vipInfo) {
            $this->error('未找到VIP相关信息1');
        }
        $pricedata = $vipInfo->pricedata;
        $vipInfo1 = Service::getVipInfo();
        $vipInfo1 = $vipInfo1 ?: null;
        foreach ($pricedata as &$v){
            $v['is_repair'] = 0;
            if($vipInfo1 && $v['price'] > $vipInfo1['price']){
                $v['price'] = $v['price'] - $vipInfo1['price'];
                $v['is_repair'] = 1;
            }
        }

        $is_receive = Db::name('vip_receive')->where('user_id',$this->auth->id)->where('level',$level)->where('goods_type','normal')->count() > 0 ? 1 : 0;
        $is_virtual_receive = Db::name('vip_receive')->where('user_id',$this->auth->id)->where('level',$level)->where('goods_type','virtual')->count() > 0 ? 1 : 0;
        $res = json_decode($vipInfo,true);
        $res['pricedata'] = $pricedata;
        if(isset($vipInfo1['level']) && $vipInfo1['level'] == $vipInfo['level']){
            $res['is_receive'] = $is_receive;
            $res['is_virtual_receive'] = $is_virtual_receive;
        }else{
            $res['is_receive'] = 0;
            $res['is_virtual_receive'] = 0;
        }

        $this->success('', $res);

    }

    public function getOpenid($code){
        $appid = 'wxea0076bb291d0508';
        $appsecret = '99dba09465e795d6a1b9002b49afa557';

// 获取access_token
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$code&grant_type=authorization_code";
        $response = file_get_contents($url);
        $result = json_decode($response, true);

        if (!isset($result['openid'])) {
            return false;
        } else {
            // 获取到的openid
            $openid = $result['openid'];
            return $openid;
        }
    }

    /**
     * 创建订单并发起支付请求
     */
    public function submit()
    {
        // $a = \addons\vip\model\Record::settle(833);
        // dump($a);exit;
        $level = $this->request->param('level/d');
        $days = $this->request->param('days/d');
        $paytype = $this->request->param('paytype', '');
        $method = $this->request->param('method');
        $address_id = $this->request->param('address_id');
//        $appid = $this->request->param('appid');//APP的应用ID
        $code = $this->request->param('code', '');
        $openid = $this->request->param('openid', '');//Openid 用于小程序和公众号登录场景
        $returnurl = $this->request->param('returnurl', '', 'trim');
        $vipInfo = \addons\vip\model\Vip::getByLevel($level);
        if (!$vipInfo) {
            $this->error('未找到VIP相关信息');
        }
        if ($this->auth->vip > $vipInfo['level']) {
            $this->error('当前VIP等级已高于购买的VIP等级');
        }
        if (!in_array($paytype, ['alipay', 'wechat', 'balance'])) {
            $this->error('支付方式错误');
        }
        //查询是否已开通过此等级
        $is_kt = Db::name('vip_record')->where('user_id',$this->auth->id)->where('level',$level)->where('status','in',['active','finished'])->count() > 0 ? 1 : 0;
        if($is_kt > 0){
            $this->error('请勿重复开通');
        }

        $amount = $vipInfo->getPriceByDays($days);
        $vipInfo1 = Service::getVipInfo();
        $vipInfo1 = $vipInfo1 ?: null;
        if($vipInfo1 && $amount > $vipInfo1['price']){
            //减去已购买价格
            $buy_price = Record::where('user_id',$this->auth->id)->where('status','in',['active','finished','locked'])->sum('amount');
            if($buy_price > 0){
                // $amount = $amount - $vipInfo1['price'];
                $amount = $amount - $buy_price;
            }


        }
        // $amount = 0.01;
        $insert = [
            'user_id' => $this->auth->id,
            'vip_id'  => $vipInfo->id,
            'level'   => $vipInfo->level,
            'days'    => $days,
            'amount'  => $amount,
            'address_id'  => $address_id,
            'status'  => 'created',
        ];
        $vipRecord = Record::create($insert, true);
        if(!$openid){
            $openid = $this->getOpenid($code);
        }
        //公众号和小程序
        if ($paytype!=='balance' && !$openid && in_array($method, ['miniapp', 'mp'])) {
//            $info = get_addon_info('third');
//            if (!$info || !$info['state']) {
//                $this->error("请在后台安装第三方登录插件");
//            }
//            $third = Third::where('platform', 'wechat')->where('apptype', $method)->where('user_id', $this->auth->id)->find();
//            if (!$third) {
//                $this->error("未找到登录用户信息", 'bind');
//            }
//            $openid = $third['openid'];
            $openid = UserOauth::where([
                'user_id' => $this->auth->id
            ])->value('openid');
            if(!$openid){
                $this->error('openid错误');
            }


        }

        try {
            $response = \addons\vip\library\Order::submit($vipInfo->id, $vipRecord->id, $amount, $paytype, $method, $openid, '', $returnurl);
        } catch (OrderException $e) {
            if ($e->getCode() == 1) {
                $this->success($e->getMessage());
            } else {
                $this->error($e->getMessage());
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success(__(''), $response);
    }

    /**
     * 企业支付通知和回调
     */
    public function epay()
    {
        $type = $this->request->param('type');
        $paytype = $this->request->param('paytype');
        if ($type == 'notify') {
            $pay = \addons\epay\library\Service::checkNotify($paytype);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            //判断是V2还是V3
            $data = $pay instanceof \Yansongda\Pay\Gateways\Wechat ? $pay->verify() : $pay->callback();
            try {
                $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                \addons\vip\library\Order::settle($data['out_trade_no'], $payamount);
            } catch (Exception $e) {
            }
            echo $pay->success();
        } else {
            $this->success("请返回网站查看支付状态!", "index/vip/viplist");
        }
        return;
    }
}
